﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics;

using Microsoft.WindowsMobile.Status;

using iPhoneUI.Shell;

namespace iPhoneUI.Widgets
{
    public class DateTimeWidget : TextWidget
    {
        private Bitmap m_background;
        private Font m_timeFont;
        
        public DateTimeWidget()
        {
            Font = ShellConfig.CreateFont(9, FontStyle.Regular);
            m_timeFont = ShellConfig.CreateFont(32, FontStyle.Regular);
            m_background = ShellConfig.CreateImage("topbar.bmp");
        }

        protected override void OnSetOwner()
        {
            RegisterSystemStateChange(SystemProperty.Time);
            RegisterSystemStateChange(SystemProperty.Date);  

            SetInitialSize(new Size(Size.Width, m_background.Height));
       
            base.OnSetOwner();
        }

        protected override void OnDispose()
        {
            m_background.SafeDispose();
            m_timeFont.SafeDispose();

            base.OnDispose();
        }

        public Font TimeFont
        {
            get
            {
                return m_timeFont;
            }
            set
            {
                Debug.Assert(value != null);
                m_timeFont.SafeDispose();
                m_timeFont = value;
            }
        }

        protected override void OnDraw(Canvas canvas, Rectangle clipBounds)
        {
            canvas.AlphaBlend(m_background, 170, ClientArea, Rectangle.FromLTRB(0, 0, m_background.Width, m_background.Height));
           
            CultureInfo culture = CultureInfo.CurrentUICulture;
            string time = SystemState.Time.ToString(culture.DateTimeFormat.ShortTimePattern, culture);
            SizeF size = canvas.MeasureString(time, TimeFont);

            DateTime now = DateTime.Now.Date;
            string date = string.Format("{0}, {1}", culture.DateTimeFormat.GetDayName(now.DayOfWeek), now.ToString("MMMM d", culture));

            using (Brush b = new SolidBrush(ForeColor))
            {
                canvas.DrawString(time, TimeFont, b, CenterString(time, TimeFont, canvas), Location.Y + 2);
                canvas.DrawString(date, Font, b, CenterString(date, Font, canvas), Location.Y + (int)size.Height);
            }
        }
    }
}
